<?php

namespace App\Http\Controllers;

use App\Libs\Tools\DataTables;
use Illuminate\Support\Facades\Input;
use Prettus\Validator\Contracts\ValidatorInterface;
use Prettus\Validator\Exceptions\ValidatorException;

trait CurlRecordMethod{

    public function index(){
        return view($this->index_page);
    }

    public function list_data(){
        $this->repository->pushCriteria($this->getBaseQueryCriteria());
        $data=$this->repository->paginate($this->getPageLimit());
        return response()->json(DataTables::convert_transform_to_datatables($data));
    }

    public function delete_data(){
        $this->repository->deleteByPrimaryKeys(Input::get('ids'));
        return $this->return_json_success();
    }

    public function add_data(){
        if($this->request->isMethod('get')){
            return $this->get_add_data();
        }
        return $this->post_add_data();

    }

    protected function get_add_data(){
        return view($this->add_page);
    }
    protected function post_add_data(){
        $all=$this->wrap_user_info($this->request->all(),true);
        try {
            $this->validator->with($all)->passesOrFail(ValidatorInterface::RULE_CREATE);
            $this->repository->create($all);
            return $this->return_json_success();
        } catch (ValidatorException $e) {
            return $this->return_json_error($e);
        }
    }

    public function edit_data(){

        if($this->request->isMethod('get')){
            return $this->get_edit_data();
        }
       return $this->post_edit_data();
    }

    protected function get_edit_data(){
        $id=$this->request->get('id');
        $editEntity = $this->repository->find($id);
        return view($this->edit_page,compact('editEntity'));
    }

    protected function post_edit_data(){
        $id=$this->request->get('id');
        $all=$this->wrap_user_info($this->request->all());
        try {
            $this->validator->with($all)->passesOrFail(ValidatorInterface::RULE_UPDATE);
            $this->repository->update($all, $id);
            return $this->return_json_success();
        } catch (ValidatorException $e) {
            return $this->return_json_error($e);
        }
    }
}
